package com.test.controller;

import com.test.WebApplication;
import com.test.config.BizConfig;
import com.test.service.RoutingDelegate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hero
 */
@RestController
@RequestMapping("/gateway")
public class GateWayController {

    private static final Logger LOGGER = LoggerFactory.getLogger(GateWayController.class);

    @Autowired
    private RoutingDelegate routingDelegate;

    @Autowired
    private BizConfig bizConfig;

    /**
     * 请求转发
     * @param request
     * @param response
     * @param siteName 站点名称，实际要访问
     * @return
     */
    @RequestMapping(value = {"/{siteName}/**"},
            method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE},
            produces = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity redirect(final HttpServletRequest request,
                                   final HttpServletResponse response,
                                   @PathVariable String siteName) {
        String server = bizConfig.getSiteInfo().get(siteName);
        if (server.endsWith("/")) {
            server = server.substring(0, server.length() - 1);
        }
        String requestUri = request.getRequestURI();
        String contentPath = request.getContextPath() + "/gateway/" + siteName;
        String prefix =requestUri.replace(contentPath, "");

        LOGGER.info("server:{}, requestUri:{}, contentPath:{}, prefix:{}", server, requestUri, contentPath, prefix);
        if (StringUtils.isEmpty(server)) {
            ResponseEntity responseEntity = new ResponseEntity("请求非法", HttpStatus.BAD_REQUEST);
            return responseEntity;
        }
        return routingDelegate.redirect(request, response, server, prefix);
    }
}
